﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Pavilion
{
    public class PhysicalData : IPropertyChanged
    {
        public event Action<PhysicalData> PhysicalFormChanged, PositionChanged, IsFlippedHorizontallyChanged;
        public event PropertyChangedHandler PropertyChanged;

        public GameToolBase ParentGameTool { get; private set; }
        public PhysicalState PhysicalState { get { return physicalState; } set { physicalState = value; OnPropertyChanged("PhysicalState"); } }

        public virtual Vector2 Origin { get; set; }
        public virtual bool IsFlippedHorizontally { get { return isFlippedHorizontally; } set { isFlippedHorizontally = value; OnIsFlippedHorizontallyChanged(); } }
        public Vector2 Position { get { return position; } }
        public Vector2 PreviousPosition { get; private set; }
        public float Size { get { return size; } set { size = value; OnPhysicalFormChanged(); } }

        private Vector2 position;
        private float size;
        private bool isFlippedHorizontally;
        private PhysicalState physicalState;

        public PhysicalData(GameToolBase parentGameTool)
        {
            this.ParentGameTool = parentGameTool;
        }

        public void Move(Vector2 distance)
        {
            this.Move(distance.X, distance.Y);
        }

        public virtual void Move(float xDistance, float yDistance)
        {
            SetPosition(Position.X + xDistance, Position.Y + yDistance);
        }

        public void SetPosition(Vector2 position)
        {
            SetPosition(position.X, position.Y);
        }

        public virtual void SetPosition(float x, float y)
        {
            if (position.X == x && position.Y == y)
                return;

            this.PreviousPosition = position;

            this.position.X = x;
            this.position.Y = y;

            OnPositionChanged();
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, propertyName);
        }

        protected void OnPhysicalFormChanged()
        {
            if (PhysicalFormChanged != null)
                PhysicalFormChanged(this);
        }

        private void OnPositionChanged()
        {
            if (PositionChanged != null)
                PositionChanged(this);
        }

        private void OnIsFlippedHorizontallyChanged()
        {
            if (IsFlippedHorizontallyChanged != null)
                IsFlippedHorizontallyChanged(this);

            OnPhysicalFormChanged();
            OnPropertyChanged("IsFlippedHorizontally");
        }
    }

    public enum PhysicalState
    {
        Grounded,
        Rising,
        Falling,
        Sinking,
        Floating
    }
}
